
package com.joysuch.wwyt.core.support;

import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.enums.DeleteFlag;
import com.joysuch.wwyt.mh.entity.MhMonitoringPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import javax.persistence.PrePersist;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

@Slf4j
public class AutoSetCommonFieldListener {


    @PrePersist
    public void prePersist(Object source) {
        writePropertyIfExists(source, "deleteFlag", DeleteFlag.EFFECTIVE.getCode());
        writePropertyIfExists(source, "tenentId", Context.getCurrentTenantId());

        //写入： 同一个租户，同一个公司内部， 没有数据权限: 监测点
        if(source instanceof MhMonitoringPoint){
            writePropertyIfExists(source, "orgCode", Context.getCompanyCode());
        }else{
            writePropertyIfExists(source, "orgCode", Context.getCurrentOrgCode());
        }

        if(source instanceof BaseUser){
            if(((BaseUser) source).getOrgCode() == null){
                writePropertyIfExists(source, "orgCode", Context.getCurrentOrgCode());
            }
            log.info("..... update user: ", source.toString());
        }
    }

    private void writePropertyIfExists(Object source, String field, Object code) {
        if (code == null) {
            //防止后台任务中已经设置好的数据被覆盖为null
            return;
        }
        PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(source.getClass(), field);
        if (descriptor != null && descriptor.getWriteMethod() != null) {
            try {
                descriptor.getWriteMethod().invoke(source, code);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    }
}
